package vip.zhenzicheng.algorithm.leetcode.array;

import java.util.ArrayList;
import java.util.List;

/**
 * <a href="https://leetcode.cn/problems/spiral-matrix/">螺旋矩阵 [中等]</a>
 *
 * @author zhenzicheng
 * @date 2022-06-20 09:22
 */
public class SpiralMatrix_54 {

  public static void main(String[] args) {
    SpiralMatrix_54 test = new SpiralMatrix_54();
    int[][] matrix = new int[][]{{7}, {9}, {6}};
    List<Integer> result = test.spiralOrder(matrix);
    System.out.println(result);
  }

  public List<Integer> spiralOrder(int[][] matrix) {
    int xLen = matrix.length;
    int yLen = matrix[0].length;
    int level = (Math.min(xLen, yLen) + 1) / 2; // 最大矩阵级别为短边+1再除2
    List<Integer> result = new ArrayList<>();
    int up = -1, right = yLen, bottom = xLen, left = -1; // 初始边界

    for (int i = 0, x, y; i < level; i++) {
      int temp;
      // 向右走
      for (y = left + 1, x = up + 1; y < right; y++) {
        result.add(matrix[x][y]);
      }
      up++;

      // 向下走
      for (x = up + 1, y = right - 1; x < bottom; x++) {
        result.add(matrix[x][y]);
      }
      right--;

      // 向左走,逻辑重复需要多一次判断上下边界
      for (x = bottom - 1, y = right - 1; y > left && x > up; y--) {
        result.add(matrix[x][y]);
      }
      bottom--;

      // 向上走,逻辑重复需要多一次判断左右边界
      for (x = bottom - 1, y = left + 1; x > up && y < right; x--) {
        result.add(matrix[x][y]);
      }
      left++;
    }
    return result;
  }
}
